package com.jf.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jf.blog.bean.Userinfo;
import com.jf.blog.form.LoginForm;
import com.jf.blog.form.userinfo.UserinfoExamForm;
import com.jf.blog.form.userinfo.UserinfoPasswordForm;
import com.jf.blog.form.userinfo.UserinfoUpdateForm;
import com.jf.blog.form.vip.VipAuthForm;
import com.jf.blog.form.vip.VipPasswordForm;
import com.jf.blog.form.vip.VipRegisterForm;
import com.jf.blog.form.vip.VipUpdateForm;
import com.jf.blog.mapper.UserinfoMapper;
import com.jf.blog.service.KaptchaService;
import com.jf.blog.service.UserinfoService;
import com.jf.blog.util.LoginUtil;
import com.jf.blog.util.MyConstants;
import com.jf.blog.util.MyUtils;
import com.jf.blog.util.ResultJson;
import com.jf.blog.util.exception.BusinessException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author JF
 * @since 2025-06-20
 */
@Service
@Transactional
public class UserinfoServiceImpl extends ServiceImpl<UserinfoMapper, Userinfo> implements UserinfoService {
    @Autowired
    private KaptchaService kaptchaService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public ResultJson login(LoginForm loginForm) {
        /*检测验证码*/
        if (!kaptchaService.checkKaptcha(loginForm.getUuid(), loginForm.getCode())) {
            throw new BusinessException("验证码错误！");
        }
        /*根据用户名查询用户信息*/
        Userinfo userinfo = getUserinfoByUsername(loginForm.getUsername());
        if (userinfo == null) {
            throw new BusinessException("用户名或密码不正确！");
        }
        /*获取密码盐值*/
        String slat = userinfo.getSlat();
        /*加密密码*/
        String password = MyUtils.getSlatPassword(loginForm.getPassword(), slat);
        /*比较密码*/
        if (!userinfo.getPassword().equalsIgnoreCase(password)) {
            throw new BusinessException("用户名或密码不正确！");
        }
        /*验证用户状态*/
        if (userinfo.getStatus() != 1) {
            throw new BusinessException("该用户已被封禁，请联系管理员！");
        }
        /*生成token*/
        String token = MyUtils.createToken();
        /*存储token到redis，设置4小时有效*/
        redisTemplate.opsForValue().set(MyConstants.TOKEN_KEY + token, userinfo.getUserinfoId().toString(), Duration.ofHours(4));
        /*封装token*/
        Map<String, String> map = new HashMap<>();
        map.put(MyConstants.TOKEN, token);
        return ResultJson.success(map);
    }

    @Override
    public void saveOrUpdate(UserinfoUpdateForm form) {
        if (StringUtils.isEmpty(form.getIdcard())) {
            throw new BusinessException("身份证号不存在!");
        }
        /*表单类转换为实体类*/
        Userinfo userinfo = new Userinfo();
        BeanUtils.copyProperties(form, userinfo);
        if (userinfo.getUserinfoId() == null) {
            /*重名验证*/
            Userinfo search = getUserinfoByUsername(userinfo.getUsername());
            if (search != null) {
                throw new BusinessException("该用户名已存在!");
            }
            /*封装密码*/
            userinfo.setSlat(MyUtils.createSlat());
            String defaultPassword = MyUtils.getDefaultPassword(form.getIdcard());
            String md5Password = MyUtils.getSlatPassword(defaultPassword, userinfo.getSlat());
            userinfo.setPassword(md5Password);
            /*添加的用户默认为管理员和已认证*/
            userinfo.setRoleId(MyConstants.ROLE_ADMIN);
            userinfo.setUserinfoStatus(MyConstants.USER_STATUS_RENZHENG);
        }
        this.saveOrUpdate(userinfo);
    }

    @Override
    public void vipRegister(VipRegisterForm form) {
        Userinfo search = getUserinfoByUsername(form.getUsername());
        if (search != null) {
            throw new BusinessException("该用户已存在");
        }

        Userinfo userinfo = new Userinfo();
        BeanUtils.copyProperties(form, userinfo);
        /*用户注册的账号只能是vip账号和已注册*/
        userinfo.setRoleId(MyConstants.ROLE_VIP);
        userinfo.setUserinfoStatus(MyConstants.USER_STATUS_ZHUCE);
        /*处理密码*/
        userinfo.setSlat(MyUtils.createSlat());
        userinfo.setPassword(MyUtils.getSlatPassword(userinfo.getPassword(), userinfo.getSlat()));
        /*个人地址默认为用户名*/
        userinfo.setHref(userinfo.getUsername());
        /*昵称默认为用户名*/
        userinfo.setNickname(userinfo.getUsername());
        this.save(userinfo);
    }

    @Override
    public void vipAuth(VipAuthForm form) {

        // todo 验证码

        List<Userinfo> phoneList = this.list(new QueryWrapper<Userinfo>().eq("phone", form.getPhone()));
        if (!phoneList.isEmpty()) {
            throw new BusinessException("手机号已被注册!");
        }
        List<Userinfo> idcardList = this.list(new QueryWrapper<Userinfo>().eq("idcard", form.getIdcard()));
        if (!idcardList.isEmpty()) {
            throw new BusinessException("身份证号已被认证!");
        }

        Userinfo userinfo = new Userinfo();
        BeanUtils.copyProperties(form, userinfo);
        userinfo.setUserinfoId(LoginUtil.getLoginUser().getUserinfoId());
        userinfo.setUserinfoStatus(MyConstants.USER_STATUS_WEIRENZHENG);
        userinfo.setAuthTime(new Date());
        this.updateById(userinfo);
    }

    @Override
    public void vipPassword(VipPasswordForm form) {
        // todo code验证
        String slat = MyUtils.createSlat();
        String password = MyUtils.getSlatPassword(form.getPassword(), slat);

        Userinfo userinfo = new Userinfo();
        userinfo.setPassword(password);
        userinfo.setSlat(slat);
        userinfo.setUserinfoId(LoginUtil.getLoginUser().getUserinfoId());
        this.updateById(userinfo);
    }

    @Override
    public void exam(UserinfoExamForm form) {
        if (LoginUtil.getLoginUser().getRoleId() == MyConstants.ROLE_VIP) {
            throw new BusinessException("权限不足,无法审核!");
        }
        Userinfo userinfo = new Userinfo();
        BeanUtils.copyProperties(form, userinfo);
        userinfo.setExamUserinfoId(LoginUtil.getLoginUser().getUserinfoId());
        userinfo.setExamTime(new Date());
        this.updateById(userinfo);
    }

    @Override
    public void password(UserinfoPasswordForm form) {
        Userinfo login = LoginUtil.getLoginUser();
        if (login.getRoleId() == MyConstants.ROLE_VIP) {
            throw new BusinessException("权限不足，禁止操作!");
        }
        int loginId = login.getUserinfoId();
        /*获取要修改密码的用户信息*/
        Userinfo search = this.getById(loginId);
        /*获取密码盐值*/
        String slat = search.getSlat();
        /*加密原密码*/
        String oldPassword = MyUtils.getSlatPassword(form.getOldPassword(), slat);
        /*比较原密码是否正确*/
        if (!search.getPassword().equals(oldPassword)) {
            throw new BusinessException("原密码不正确！");
        }

        /*重新生成盐值*/
        slat = MyUtils.createSlat();
        /*加密新密码*/
        String password = MyUtils.getSlatPassword(form.getPassword(), slat);
        /*封装数据*/
        Userinfo userinfo = new Userinfo();
        userinfo.setUserinfoId(loginId);
        userinfo.setSlat(slat);
        userinfo.setPassword(password);
        /*执行修改*/
        this.updateById(userinfo);

    }

    @Override
    public void vipUpdate(VipUpdateForm form) {
        List<Userinfo> hrefList = this.list(
                new QueryWrapper<Userinfo>()
                        .eq("href", form.getHref())
                        .ne("userinfo_id", LoginUtil.getLoginUser().getUserinfoId())
        );
        if (!hrefList.isEmpty()) {
            throw new BusinessException("自定义地址已存在!");
        }

        Userinfo userinfo = new Userinfo();
        userinfo.setUserinfoId(LoginUtil.getLoginUser().getUserinfoId());
        BeanUtils.copyProperties(form, userinfo);
        this.updateById(userinfo);

    }

    private Userinfo getUserinfoByUsername(String username) {
        return this.getOne(new QueryWrapper<Userinfo>().eq("username", username));
    }
}
